#include <iostream>

using std::cout;
using std::endl;


class Singleton
{
public:
    static Singleton * getInstance()
    {
        if(_pInstance == nullptr) {
            _pInstance = new Singleton;
        }
        return _pInstance;
    }

    static void destroy()
    {
        if(_pInstance) {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

    void print() const
    {
        cout << "(" << _ix
             << "," << _iy
             << ")" << endl;
    }

    void init(int ix, int iy)
    {
        _ix = ix;
        _iy = iy;
    }

private:
    Singleton()
    : _ix(0), _iy(0)
    {   cout << "Singleton()" << endl;  }

    ~Singleton() {   cout << "~Singleton()" << endl;  }


    //友元不受这public/protected/private关键字的限制 
    //设置为友元的目的是为了在Singleton类之外调用析构函数
    friend class AutoRelease;
private:
    static Singleton * _pInstance;
    int _ix;
    int _iy;
};

Singleton * Singleton::_pInstance = nullptr;

class AutoRelease
{
public:
    AutoRelease(Singleton * p)
    : _p(p)
    {   cout << "AutoRelease()" << endl;}

    ~AutoRelease() {
        cout << "~AutoRelease()" << endl;
        if(_p) {
            //delete表达式要调用Singleton的析构函数
            delete _p;
            _p = nullptr;
        }
    }

private:
    Singleton * _p;
};

int main()
{
    Singleton * p1 = Singleton::getInstance();
    //用栈对象ar来管理单例对象
    AutoRelease ar(p1);//希望有更好的解法，让该语句消失
    Singleton * p2 = Singleton::getInstance();
    cout << "p1: " << p1 << endl;
    cout << "p2: " << p2 << endl;
    Singleton::getInstance()->init(10, 11);//实际操作时的用法
    Singleton::getInstance()->print();
    cout << endl;

    //需求：不调用destroy函数，单例对象也能自动回收
    //Singleton::destroy();

    return 0;
}

